from apps.merchant.sku.dao import SkuDao
from apps.merchant.tag.dao import TagDao
from apps.merchant.item.dao import ItemDao
from apps.system.lessee.dao import LesseeDao
import datetime
import json

def setSeckillItem(params={}):
    ids = params.get('ids')
    # print('dayDiscountItemParams', dayDiscountItemParams.get('2025-04-17'))
    if not ids or type(ids) != list:
        # disDict = {
        #     '2025-04-18': [1118,1098,1074,981],
        #     '2025-04-19': [1096,1131,982,946],
        # }
        # print('当天时间', datetime.datetime.now().strftime('%Y-%m-%d'))
        lessee = LesseeDao().getLessee()
        dayDiscountItemParams = json.loads(lessee.dayDiscountItemParams)
        # 优化dayDiscountItemParams参数
        dayDiscountItemParams_new = {}
        for key in dayDiscountItemParams.keys():
            if(len(key.split('-')) != 3):
                return "日期格式错误"
            n1 = key.split('-')[0]
            n2 = key.split('-')[1]
            n3 = key.split('-')[2]
            if len(n1)!=4 or len(n2)>2 or len(n3)>2:
                return "日期格式错误"
            if len(n2)==1:
                n2 = '0'+n2
            if len(n3)==1:
                n3 = '0'+n3
            dayDiscountItemParams_new[n1+'-'+n2+'-'+n3] = dayDiscountItemParams[key]
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        ids = dayDiscountItemParams_new.get(today)
        if not ids or type(ids) != list:
            ids = []
            return
    tag = TagDao().findAll().filter(name='秒杀').first()
    items = ItemDao().findAll().filter(tags__name='秒杀')
    for item in items:
        for sku in item.item_sku.all():
            sku.sellingPrice = sku.marketPrice
            sku.save()
        item.tags.remove(tag.id)
        # 同步商品的价格
        skus = SkuDao().findAll().filter(item__id=item.id).order_by('sellingPrice')
        sku = skus.first()
        ItemDao().update(item.id, {'sellingPrice': sku.sellingPrice, 'marketPrice': sku.marketPrice, 'discountPrice': sku.discountPrice})
    items2 = ItemDao().findAll().filter(id__in=ids)
    for item in items2:
        for sku in item.item_sku.all():
            sku.marketPrice = sku.sellingPrice
            if sku.discountPrice > 0:
                sku.sellingPrice = sku.discountPrice
            sku.save()
        item.tags.add(tag.id)
        # 同步商品的价格
        skus = SkuDao().findAll().filter(item__id=item.id).order_by('sellingPrice')
        sku = skus.first()
        ItemDao().update(item.id, {'sellingPrice': sku.sellingPrice, 'marketPrice': sku.marketPrice, 'discountPrice': sku.discountPrice})
    print('设置秒杀成功')